package org.example.common.web.interceptor;

import org.example.common.core.constants.GrayConstant;
import org.example.common.core.utils.StringUtils;
import org.example.common.core.utils.ribbon.GrayRequestContextHandler;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 灰度标签处理
 */
public class GrayTagRuleInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String gray_header = request.getHeader(GrayConstant.GRAY_HEADER);
            if(StringUtils.isNotEmpty(gray_header)){
                GrayRequestContextHandler.setGrayTag(Boolean.valueOf(gray_header));
            }
        }finally {
            return true;
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        GrayRequestContextHandler.remove();
    }

}
